<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-select v-model="currentRole" placeholder="选择用户角色" @change="handleRoleChange">
            <el-option label="管理员" :value="1" />
            <el-option label="商家" :value="2" />
            <el-option label="普通用户" :value="3" />
          </el-select>
        </div>
      </template>

      <!-- 用户列表 -->
      <el-table v-loading="loading" :data="userList" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar">{{ row.nickname?.charAt(0) }}</el-avatar>
              <div class="user-detail">
                <div>{{ row.nickname || '未设置昵称' }}</div>
                <div class="user-sub">{{ row.username }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" width="120" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="showUserDetails(row)">详情</el-button>
            <el-button 
              v-if="row.roleId !== 1"
              size="small" 
              type="primary" 
              @click="showBehaviorAnalysis(row)"
            >分析</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="用户详情"
      width="600px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID" :span="2">{{ currentUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ currentUser.nickname }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
            {{ currentUser.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">
          {{ formatDate(currentUser.createTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 行为分析对话框 -->
    <el-dialog
      v-model="analysisVisible"
      title="用户行为分析"
      width="80%"
      destroy-on-close
    >
      <div v-loading="analyzingUser">
        <!-- 行为统计卡片 -->
        <el-row :gutter="20" class="stat-cards">
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>总浏览量</span>
                </div>
              </template>
              <div class="stat-value">{{ behaviorStats.totalViews || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>搜索次数</span>
                </div>
              </template>
              <div class="stat-value">{{ behaviorStats.totalSearches || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <span>购买次数</span>
                </div>
              </template>
              <div class="stat-value">{{ behaviorStats.totalPurchases || 0 }}</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 行为趋势图 -->
        <el-card class="trend-card">
          <template #header>
            <div class="card-header">
              <span>行为趋势</span>
              <div class="header-right">
                <el-select v-model="behaviorType" placeholder="行为类型" @change="fetchBehaviorTrend">
                  <el-option label="浏览" value="BROWSE" />
                  <el-option label="搜索" value="SEARCH" />
                  <el-option label="购买" value="PURCHASE" />
                </el-select>
                <el-select v-model="trendDays" placeholder="时间范围" @change="fetchBehaviorTrend">
                  <el-option label="最近7天" :value="7" />
                  <el-option label="最近30天" :value="30" />
                  <el-option label="最近90天" :value="90" />
                </el-select>
              </div>
            </div>
          </template>
          <div ref="trendChartRef" style="height: 300px"></div>
        </el-card>

        <!-- 时间分布热力图 -->
        <el-card class="heatmap-card">
          <template #header>
            <div class="card-header">
              <span>活跃时段分布</span>
            </div>
          </template>
          <div ref="heatmapChartRef" style="height: 300px"></div>
        </el-card>

        <!-- 分类偏好 -->
        <el-card class="preference-card">
          <template #header>
            <div class="card-header">
              <span>分类偏好</span>
            </div>
      </template>
          <div ref="preferenceChartRef" style="height: 300px"></div>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  getUserListByRole,
  updateUserStatus,
  getUserBehaviorStats,
  getUserBehaviorTrend,
  getUserBehaviorHeatmap,
  getUserCategoryPreferences
} from '@/api/admin'
import { useRouter } from 'vue-router'

const router = useRouter()

// 状态定义
const loading = ref(false)
const currentRole = ref(3)
const userList = ref([])
const detailVisible = ref(false)
const analysisVisible = ref(false)
const analyzingUser = ref(false)
const currentUser = ref({})
const behaviorStats = ref({})
const behaviorType = ref('BROWSE')
const trendDays = ref(7)

// 图表实例
let trendChart = null
let heatmapChart = null
let preferenceChart = null
const trendChartRef = ref(null)
const heatmapChartRef = ref(null)
const preferenceChartRef = ref(null)

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    const res = await getUserListByRole(currentRole.value)
    if (res?.code === 200) {
      userList.value = res.data || []
  } else {
      ElMessage.warning(res?.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理角色切换
const handleRoleChange = () => {
  fetchUsers()
}

// 处理状态变更
const handleStatusChange = async (user, status) => {
  try {
    await updateUserStatus(user.id, status)
    ElMessage.success('更新状态成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
    user.status = status === 1 ? 0 : 1 // 恢复状态
  }
}

// 查看用户详情
const showUserDetails = (user) => {
  currentUser.value = user
  detailVisible.value = true
}

// 分析用户行为
const showBehaviorAnalysis = (row) => {
  if (row.roleId === 2) {
    // 商家用户，跳转到商家分析页面
    router.push(`/admin/statistics/merchant/${row.id}`)
  } else if (row.roleId === 3) {
    // 普通用户，跳转到用户分析页面
    router.push(`/admin/statistics/user/${row.id}`)
  }
}

// 获取行为统计
const fetchBehaviorStats = async () => {
  try {
    const res = await getUserBehaviorStats(currentUser.value.id)
    if (res?.code === 200) {
      behaviorStats.value = res.data
    }
  } catch (error) {
    console.error('获取行为统计失败:', error)
  }
}

// 获取行为趋势
const fetchBehaviorTrend = async () => {
  try {
    const res = await getUserBehaviorTrend(
      currentUser.value.id,
      behaviorType.value,
      trendDays.value
    )
    if (res?.code === 200) {
      initTrendChart(res.data)
    }
  } catch (error) {
    console.error('获取行为趋势失败:', error)
  }
}

// 获取行为热力图
const fetchBehaviorHeatmap = async () => {
  try {
    const res = await getUserBehaviorHeatmap(currentUser.value.id, behaviorType.value)
    if (res?.code === 200) {
      initHeatmapChart(res.data)
    }
  } catch (error) {
    console.error('获取热力图数据失败:', error)
  }
}

// 获取分类偏好
const fetchCategoryPreferences = async () => {
  try {
    const res = await getUserCategoryPreferences(currentUser.value.id)
    if (res?.code === 200) {
      initPreferenceChart(res.data)
    }
  } catch (error) {
    console.error('获取分类偏好失败:', error)
  }
}

// 初始化趋势图表
const initTrendChart = (data) => {
  if (!trendChartRef.value) return

  if (!trendChart) {
    trendChart = echarts.init(trendChartRef.value)
  }

  const dates = Object.keys(data)
  const values = Object.values(data)

  const option = {
    title: {
      text: '行为趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: values,
        type: 'line',
        smooth: true
      }
    ]
  }

  trendChart.setOption(option)
}

// 初始化热力图
const initHeatmapChart = (data) => {
  if (!heatmapChartRef.value) return

  if (!heatmapChart) {
    heatmapChart = echarts.init(heatmapChartRef.value)
  }

  const hours = []
  const days = []
  const values = []

  Object.entries(data).forEach(([date, hourData]) => {
    Object.entries(hourData).forEach(([hour, count]) => {
      if (!hours.includes(hour)) hours.push(hour)
      if (!days.includes(date)) days.push(date)
      values.push([hours.indexOf(hour), days.indexOf(date), count])
    })
  })

  const option = {
    title: {
      text: '活跃时段分布'
    },
    tooltip: {
      position: 'top'
    },
    grid: {
      height: '50%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: hours,
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: days,
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%'
    },
    series: [{
      name: '活跃度',
      type: 'heatmap',
      data: values,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  heatmapChart.setOption(option)
}

// 初始化偏好图表
const initPreferenceChart = (data) => {
  if (!preferenceChartRef.value) return

  if (!preferenceChart) {
    preferenceChart = echarts.init(preferenceChartRef.value)
  }

  const option = {
    title: {
      text: '分类偏好'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '分类偏好',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '40',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          value: item.count,
          name: `分类${item.categoryId}`
        }))
      }
    ]
  }

  preferenceChart.setOption(option)
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 监听窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  heatmapChart?.resize()
  preferenceChart?.resize()
}

// 组件挂载
onMounted(() => {
  fetchUsers()
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  heatmapChart?.dispose()
  preferenceChart?.dispose()
})
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.user-sub {
  font-size: 12px;
  color: #999;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-header {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  text-align: center;
  margin-top: 10px;
}

.trend-card,
.heatmap-card,
.preference-card {
  margin-top: 20px;
}

.header-right {
  display: flex;
  gap: 10px;
}

:deep(.el-select) {
  width: 120px;
}
</style> 